package cn.project.lemontree.utils;

import cn.project.lemontree.bean.User;
import cn.project.lemontree.service.AdministratorService;
import cn.project.lemontree.service.ParentService;
import cn.project.lemontree.service.TeacherService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private ParentService parentService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private AdministratorService administratorService;

    @Override
    public boolean supports(AuthenticationToken token){
        return token != null && token instanceof MyAuthenticationToken;
    }

    //用户权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //用户登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MyAuthenticationToken token = (MyAuthenticationToken)authenticationToken;
        SimpleAuthenticationInfo info = null;
        String telephone = (String)token.getPrincipal();
        User user = null;
        if(token.getRole() == 1){
            user = new User(teacherService.login(telephone));
        }else if(token.getRole() == 2){
            user = new User(administratorService.login(telephone));
        }else{
            user = new User(parentService.login(telephone));
        }
        if(user != null){
            SecurityUtils.getSubject().getSession().setAttribute("user",user);
            info = new SimpleAuthenticationInfo(user.getTelephone(),user.getPassword(),super.getName());
        }
        return info;
    }
}
